<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>放大镜</title>
    <style>
        #box {
            width: 250px;
            height: 250px;
            position: relative;
        }
        
        #box span {
            width: 125px;
            height: 125px;
            background: rgba(255, 255, 0, .4);
            position: absolute;
            display: none;
        }
        
        #box img {
            width: 100%;
            height: 100%;
        }
        
        #big {
            width: 250px;
            height: 250px;
            position: absolute;
            top: 8px;
            left: 300px;
            display: none;
            overflow: hidden;
        }
        
        #big img {
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="box">
        <span></span>
        <img src="1.jpg" alt="">
    </div>
    <div id="big">
        <img src="1.jpg" alt="">
    </div>
    <script>
        class Zoom {
            constructor() {
                this.box = document.querySelector('#box');
                this.span = this.box.querySelector('#box span');
                this.big = document.querySelector('#big');
                this.img = this.big.querySelector('img')
                this.init()
            }
            init() {
                this.box.onmousemove = e => {
                    this.span.style.display = 'block'
                    this.big.style.display = 'block'
                    this.left = e.clientX - this.box.offsetLeft - this.span.offsetWidth / 2;
                    this.top = e.clientY - this.box.offsetTop - this.span.offsetHeight / 2;
                    this.move();

                }
                this.box.onmouseleave = e => {
                    this.span.style.display = 'none'
                    this.big.style.display = 'none'
                }
            }
            move() {
                if (this.left < 0) this.left = 0;
                if (this.top < 0) this.top = 0;
                if (this.left > this.box.clientWidth - this.span.offsetWidth) {
                    this.left = this.box.clientWidth - this.span.offsetWidth;
                }
                if (this.top > this.box.clientHeight - this.span.offsetHeight) {
                    this.top = this.box.clientHeight - this.span.offsetHeight;
                }
                this.span.style.left = this.left + 'px'
                this.span.style.top = this.top + 'px'
                this.img.style.left = -2 * this.left + 'px'
                this.img.style.top = -2 * this.top + 'px'
            }
        }
        new Zoom()
    </script>
</body>

</html>